// Socket.IO工具类
import { io, Socket } from 'socket.io-client'

export class SocketIOManager {
  private socket: Socket | null = null
  private url: string
  private reconnectAttempts = 0
  private maxReconnectAttempts = 5
  private reconnectInterval = 5000
  private listeners: Map<string, Function[]> = new Map()

  constructor(url: string) {
    this.url = url
  }

  // 连接Socket.IO
  connect(): Promise<void> {
    return new Promise((resolve, reject) => {
      try {
        this.socket = io(this.url, {
          transports: ['websocket', 'polling'],
          timeout: 20000,
          forceNew: true
        })
        
        this.socket.on('connect', () => {
          console.log('Socket.IO连接已建立')
          this.reconnectAttempts = 0
          this.emit('connected')
          resolve()
        })
        
        this.socket.on('dashboard:update', (data) => {
          console.log('收到数据大屏更新:', data)
          this.emit('message', data)
        })
        
        this.socket.on('disconnect', () => {
          console.log('Socket.IO连接已关闭')
          this.emit('disconnected')
          this.handleReconnect()
        })
        
        this.socket.on('connect_error', (error) => {
          console.error('Socket.IO连接错误:', error)
          this.emit('error', error)
          reject(error)
        })
      } catch (error) {
        reject(error)
      }
    })
  }

  // 发送消息
  send(event: string, data: any): void {
    if (this.socket && this.socket.connected) {
      this.socket.emit(event, data)
    } else {
      console.warn('Socket.IO未连接，无法发送消息')
    }
  }

  // 断开连接
  disconnect(): void {
    if (this.socket) {
      this.socket.disconnect()
      this.socket = null
    }
  }

  // 处理重连
  private handleReconnect(): void {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++
      console.log(`尝试重新连接Socket.IO (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`)
      
      setTimeout(() => {
        this.connect().catch(error => {
          console.error('重连失败:', error)
        })
      }, this.reconnectInterval)
    } else {
      console.error('Socket.IO重连次数已达上限')
      this.emit('reconnect-failed')
    }
  }

  // 事件监听
  on(event: string, callback: Function): void {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, [])
    }
    this.listeners.get(event)!.push(callback)
  }

  // 移除事件监听
  off(event: string, callback: Function): void {
    const callbacks = this.listeners.get(event)
    if (callbacks) {
      const index = callbacks.indexOf(callback)
      if (index > -1) {
        callbacks.splice(index, 1)
      }
    }
  }

  // 触发事件
  private emit(event: string, data?: any): void {
    const callbacks = this.listeners.get(event)
    if (callbacks) {
      callbacks.forEach(callback => callback(data))
    }
  }

  // 获取连接状态
  get isConnected(): boolean {
    return this.socket?.connected || false
  }
}

// 创建全局Socket.IO管理器实例
export const dashboardWS = new SocketIOManager('http://localhost:3000')
